package cn.tedu.hms.user.webapi.service;
import java.time.LocalDateTime;

import cn.tedu.hms.common.ex.ServiceException;
import cn.tedu.hms.common.web.State;
import cn.tedu.hms.pojo.dto.UserDTO;
import cn.tedu.hms.pojo.entity.User;
import cn.tedu.hms.pojo.vo.UserVO;
import cn.tedu.hms.user.service.IUserService;
import cn.tedu.hms.user.webapi.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper mapper;

    //全局事务处理
    @Override
    public void addUser(UserDTO userDTO) {
        //判断用户是否已经存在
        UserVO queryUser = mapper.getUserByName(userDTO.getUsername());
        if (queryUser != null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "用户名已存在");
        }
        //赋值
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);

        user.setLastLoginIp("");
        LocalDateTime now = LocalDateTime.now();
        user.setGmtLastLogin(now);
        user.setGmtCreate(now);
        user.setGmtModified(now);
        //设置密码

        int rows = mapper.addUser(user);
        if (rows != 1) {
            throw new ServiceException(State.ERR_INSERT, "用户注册失败,请重新注册");
        }

    }
}
